package io.chenglicun.modules.clc.controller.dataset;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.chenglicun.common.annotation.LogOperation;
import io.chenglicun.common.constant.Constant;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.utils.ConvertUtils;
import io.chenglicun.common.utils.ExcelUtils;
import io.chenglicun.common.utils.Result;
import io.chenglicun.common.utils.excel.MyExcelUtils;
import io.chenglicun.common.validator.AssertUtils;
import io.chenglicun.common.validator.ValidatorUtils;
import io.chenglicun.common.validator.group.AddGroup;
import io.chenglicun.common.validator.group.DefaultGroup;
import io.chenglicun.common.validator.group.UpdateGroup;
import io.chenglicun.modules.clc.dao.dataset.ClcDataColumnDao;
import io.chenglicun.modules.clc.dao.dataset.ClcDataContentBakDao;
import io.chenglicun.modules.clc.dao.dataset.ClcDataContentDao;
import io.chenglicun.modules.clc.dto.dataset.ClcDataContentDTO;
import io.chenglicun.modules.clc.dto.dataset.ClcDataContentVo;
import io.chenglicun.modules.clc.entity.dataset.ClcDataColumnEntity;
import io.chenglicun.modules.clc.entity.dataset.ClcDataContentBakEntity;
import io.chenglicun.modules.clc.entity.dataset.ClcDataContentEntity;
import io.chenglicun.modules.clc.entity.dataset.ClcDataSetColumnEntity;
import io.chenglicun.modules.clc.excel.dataset.ClcDataColumnImportExcel;
import io.chenglicun.modules.clc.excel.dataset.ClcDataContentExcel;
import io.chenglicun.modules.clc.service.dataset.ClcDataContentService;
import io.chenglicun.modules.security.user.SecurityUser;
import io.chenglicun.modules.sys.excel.ExcelDataOwnerInfoListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 数据内容
 *
 * @author pipi 1151485299@qq.com
 * @since 1.0 2024-03-04
 */
@RestController
@RequestMapping("clc/clcdatacontent")
@Api(tags = "数据内容")
public class ClcDataContentController {
    @Autowired
    private ClcDataContentService clcDataContentService;
    @Autowired
    private ClcDataContentDao dao;
    @Autowired
    private ClcDataContentBakDao bakDao;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
//    @RequiresPermissions("clc:clcdatacontent:page")
    public Result<PageData<ClcDataContentDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<ClcDataContentDTO> page = clcDataContentService.getPage(params);

        return new Result<PageData<ClcDataContentDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
//    @RequiresPermissions("clc:clcdatacontent:info")
    public Result<ClcDataContentDTO> get(@PathVariable("id") Long id) {
        ClcDataContentDTO data = clcDataContentService.get(id);

        return new Result<ClcDataContentDTO>().ok(data);
    }

    @PostMapping("{setId}")
    @ApiOperation("保存")
    @LogOperation("保存")
//    @RequiresPermissions("clc:clcdatacontent:save")
    public Result save(@PathVariable("setId") Long setId, @RequestBody List<List<ClcDataContentDTO>> dtos) {
        //效验数据
//        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        Long tim = new Date().getTime();
        // 先删除 再新增 确保子项完全一致
        List<Long> delIds = new ArrayList<>();
        for (List<ClcDataContentDTO> dto : dtos) {
            for (ClcDataContentDTO d : dto) {
                if (d.getId() != null)
                    delIds.add(d.getId());
            }
        }
        if (delIds.size() > 0)
            dao.deleteBatchIds(delIds);
        if (dtos == null || dtos.size() <= 0)
            return new Result().error();
        for (int i = 0; i < dtos.size(); i++) {
            List<ClcDataContentDTO> dtoList = dtos.get(i);
            if (dtoList == null || dtoList.size() <= 0)
                continue;
            for (ClcDataContentDTO dto : dtoList) {
                dto.setRowNum(Long.valueOf(i + "" + tim));
                clcDataContentService.save(dto);
            }
        }

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
//    @RequiresPermissions("clc:clcdatacontent:update")
    public Result update(@RequestBody ClcDataContentDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        clcDataContentService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
//    @RequiresPermissions("clc:clcdatacontent:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        if (ids.length <= 0)
            return new Result();
        Long tim = new Date().getTime();
        List<ClcDataContentEntity> clcDataContentEntities = dao.selectList(new QueryWrapper<ClcDataContentEntity>().lambda().in(ClcDataContentEntity::getId, ids));
        for (int i = 0; i < clcDataContentEntities.size(); i++) {
            ClcDataContentEntity content = clcDataContentEntities.get(i);
            ClcDataContentBakEntity bak = new ClcDataContentBakEntity();
            bak.setSetId(content.getSetId());
            bak.setRowNum(Long.valueOf(1 + "" + tim));
            bak.setColumnId(content.getColumnId());
            bak.setValue(content.getValue());
            bak.setCreator(SecurityUser.getUserId());
            bak.setCreateName(SecurityUser.getUser().getRealName());
            bakDao.insert(bak);
        }
        clcDataContentService.delete(ids);

        return new Result();
    }

    @Autowired
    private ClcDataContentDao contentDao;

    @DeleteMapping("delbyset/{setId}")
    @ApiOperation("删除")
    @LogOperation("删除")
//    @RequiresPermissions("clc:clcdatacontent:delete")
    public Result delbyset(@PathVariable("setId") Long setId) {
        //效验数据
        contentDao.delete(new QueryWrapper<ClcDataContentEntity>().lambda().eq(ClcDataContentEntity::getSetId, setId));

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
//    @RequiresPermissions("clc:clcdatacontent:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<ClcDataContentDTO> list = clcDataContentService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "数据内容", list, ClcDataContentExcel.class);
    }

    @PostMapping("import")
    @ApiOperation("导入")
    @LogOperation("导入")
    public Result<String> groupStatisticsImport(@RequestParam("moduleId") Long moduleId, @RequestParam("file") MultipartFile file) throws Exception {
        String msg = clcDataContentService.importExcel(moduleId, file);
        if ("导入完成".equals(msg))
            return new Result<String>().ok(msg);
        else
            return new Result<String>().error(msg);
    }


    @PostMapping("json")
    @ApiOperation("根据数据集ID获取json信息")
    public Result<Object> getJsonAll(@RequestBody Map<String, Object> params) {
        String[] setIds = null;
        try {
            ArrayList<Object> arr = (ArrayList<Object>) params.get("setIds");
            setIds = new String[arr.size()];
            for (int i = 0; i < arr.size(); i++) {
                setIds[i] = arr.get(i).toString();
            }
        } catch (Exception e) {
        }
        String keyStr = null;
        try {
            keyStr = params.get("keyStr").toString();
        } catch (Exception e) {
        }
        if (StringUtils.isEmpty(keyStr) && (setIds == null || setIds.length <= 0))
            return new Result<>().ok(null);
        Map<String, Object> map = clcDataContentService.getJsonAllBySetIds(setIds, keyStr);
        return new Result<>().ok(map);
    }

    private ClcDataColumnDao columnDao;

    @PostMapping("getbypoint")
    @ApiOperation("根据地图标记ID获取数据信息")
    public Result<List<ClcDataContentDTO>> getByPoint(@RequestBody Map<String, Object> params) {
        ArrayList<Object> setIds = (ArrayList<Object>) params.get("setId");
        Long pointId = null;
        try {
            pointId = Long.parseLong(params.get("pointId").toString());
        } catch (Exception e) {
        }
        List<ClcDataContentDTO> byPoint = clcDataContentService.getByPoint(pointId, setIds);
        return new Result<List<ClcDataContentDTO>>().ok(byPoint);
    }
}